package middleware

import "C"
import (
	"catering_sys_api/cmd/api/pack/consts"
	"catering_sys_api/core/errno"
	"catering_sys_api/core/signer"
	"context"
	"github.com/cloudwego/hertz/pkg/app"
)

type requestParam struct {
	Ct        string `query:"ct" vd:"in($,'alipay-apt','wechat-apt','business');msg:'ct参数错误'"`
	Sign      string `query:"sign,required" vd:"len($)>0;msg:'sign不能为空'"`       //签名
	Timestamp int64  `query:"timestamp,required" vd:"$>=0;msg:'timestamp不能为空'"` //时间戳
	V         string `query:"v,required" vd:"in($,'1.0');msg:'v只能为1.0'"`
	Di        string `query:"di,required" vd:"len($)==32;msg:'di错误'"`
}

func AuthSign() app.HandlerFunc {
	return func(ctx context.Context, c *app.RequestContext) {
		//签名鉴权
		//获取所有的post参数
		var (
			commonParam requestParam
			err         error
			secret      string //签名secret
			ok          bool
			postBody    map[string]interface{}
		)

		err = c.BindAndValidate(&commonParam)
		if err != nil {
			errno.Fail(errno.HTTP_PARAM_MISS, "", err.Error(), ctx, c)
			c.Abort()
			return
		}

		//验证签名
		postBody = make(map[string]interface{})
		if secret, ok = consts.SignSecret[commonParam.Ct]; !ok {
			errno.Fail(errno.HTTP_PARAM_MISS, "", "没有获取【"+commonParam.Ct+"】secret", ctx, c)
			c.Abort()
			return
		}
		//c.PostArgs().VisitAll(func(key, value []byte) {
		//	postBody[string(key)] = string(value)
		//})
		_ = c.Bind(&postBody)
		sign := signer.Sign(commonParam.Ct, secret, signer.Marshal(postBody), commonParam.V, commonParam.Timestamp)

		if sign != commonParam.Sign {
			errno.Fail(errno.SIGN_FAIL, "", "签名失败", ctx, c)
			c.Abort()
			return
		}

	}
}
